// pages/factory/factory.js
import { throttle } from '../../../utils/util.js';
import UserService from '../../../service/UserService.js';
import CommonService from '../../../service/CommonService.js';
import WalletService from '../../../service/WalletService';
import OrderService from '../../../service/OrderService';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menus: [
      { type: 1, label: '活跃工厂' },
      { type: 2, label: '优质工厂' },
      { type: 3, label: '接加急单' },
      { type: 4, label: '距离最近' }
    ],
    result: { list: [], page: {} },
    city: {},
    orderId: '',
    order: {},
    user: app.globalData.user,
    envelope: {},
    envelopes: {},
    bonused: false,
    evnelopShow: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      userType: 2,
      authStatus: 2,
      type: 1
    },
    arcAddr: 0
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const _ = this;
    const {param} = _.data;
    const { orderId, productType} = options;
    
    _.commonService = new CommonService();
    _.userService = new UserService();
    _.walletService = new WalletService();
    _.orderService = new OrderService();

    if (orderId){
      _.setData({ orderId });
      _.orderService.getOrderById(orderId).then(res=>{
        if(res.status == 0){
          _.setData({order: res.data})
        }
      })
    }
    if (productType) {
      param.productType = productType;
      _.setData({ param });
    }
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { arcAddr } = app.globalData.config;
    const {param} = this.data;
    const city = app.globalData.chooseCity;
    param.adcode = city.id;
    this.setData({ city, param, arcAddr: arcAddr.configValue})
    this._loadData(param);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.chooseCity = app.globalData.curCity;
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const _ = this;
    let redirectUrl;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
      redirectUrl = encodeURIComponent('/packageFactory/pages/factory/factory-detail?id=' + res.target.dataset.value)
    }
    return {
      title: '分享工厂',
      path: `/pages/welcome/launch?redirectUrl=${redirectUrl}`,
      //imageUrl: app.globalData.user.cardImg,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          const { shareScore } = app.globalData.setting;
          _.commonService.active(1).then(function (res) {
            if (res.status == 0) {
              wx.showModal({
                title: '谢谢分享',
                content: `恭喜你获得${shareScore}枚救兵勋章`,
                showCancel: false,
                confirmText: '知道了',
                confirmColor: '#0f9bc1'
              })
            }
          });
        }
      },
    }
  },
  onShare: function (e) {
    console.log(e);
    const _ = this;
    wx.showShareMenu({
      withShareTicket: true,
      success: function () {
        console.log('aaaa')
      }
    })
  },
  onPullDownRefresh: function () {
    wx.showToast({
      title: 'loading...',
      icon: 'loading'
    })
    console.log('onPullDownRefresh', new Date())
  },
  onCreateOrder: throttle(function(e){
    wx.navigateTo({
      url: '/packageOrder/pages/order/create-order'
    })
  },1000),
  onUserTap: function(e){
    throttle(function () {
      const { user } = app.globalData;
      if (user.authStatus != 2) {
        wx.navigateTo({
          url: '/packageUser/pages/auth/auditting'
        })
      } else {
        wx.navigateTo({
          url: '/packageUser/pages/user/user'
        })
      }
    }, 1000)();
  },
  onMenuChange: function(e){
    const _ = this;
    const {config, location} = app.globalData;
    const {param, order} = _.data;
    param.type = e.detail.type;
    if (param.type == 4){
      if (order.id && config.locationStart.configValue == 1){
        param.lat = order.lat;
        param.lng = order.lng;
      }else{
        param.lat = location.lat;
        param.lng = location.lng;
      }
      
    }
    _._loadData(param);
  },
  onLocationTap: throttle(function (e) {
    wx.navigateTo({
      url: '/pages/citys/citys'
    })
  }, 1000),
  onItemTap:function(e){
    const { id } = e.target.dataset;
    const { orderId } = this.data;
    wx.navigateTo({
      url: '/packageFactory/pages/factory/factory-detail?id=' + e.target.dataset.id + '&orderId=' + orderId
    })
  },
  _loadEnvelopeInfo: function (userId) {
    const _ = this;
    this.walletService.getEnvelopesByUserId(userId).then(function (res) {
      if (res.status == 0) {
        _.setData({
          evnelopShow: true,
          bonused: res.data.bonused,
          envelopes: res.data.envelopes,
          envelope: res.data.envelope
        });
      }
    });
  }, 
  onEvnelopBonus: function (e) {
    const userId = e.target.dataset.id;
    this.setData({ userId: userId });
    this._loadEnvelopeInfo(userId);
  },
  /**关闭红包窗口 */
  onEnvelopClose: function (e) {
    this.setData({ evnelopShow: false });
  },
  /**拆红包 */
  doBonus: function (e) {
    const _ = this;
    const { userId } = this.data;
    _.walletService.bonus(e.detail.envelopesId).then(function (result) {
      if (result.status == 0) {
        _._loadEnvelopeInfo(userId);
      }
    })
  },
  _loadData:function(param){
    const _ = this;
    _.userService.list(param).then(function (res) {
      if (res.status == 0) {
        _.setData({ result: res.data })
      }
    })
  },
  onSearch: function(e){
    const value = e.detail.value;
    const {param} = this.data;
    param.productType = value;
    this._loadData(param);
  },
  toRuZhu: function (e) {
    wx.showActionSheet({
      itemList: ['工厂方入驻', '订单方入驻'],
      success: function (res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          wx.navigateTo({
            url: '/packageUser/pages/auth/auth-rules'
          })
        } else {
          wx.navigateTo({
            url: '/packageUser/pages/auth/business-auth'
          })
        }

      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  }
})